<?php

require_once(dirname(__DIR__) . '/api/DB.php');
require_once(dirname(__DIR__) . '/api/response.php');
require_once(dirname(__DIR__) . '/api/func.php');

try {

    $db = new DB();
    $pdo = $db::$pdo;

    foreach (['user_id', 'article_id', 'content'] as $value) {
        if (!isset($_POST[$value])) {
            throw new Exception(fieldMap($value) . '为必传项');
        }

        if (empty($_POST[$value])) {
            throw new Exception(fieldMap($value) . '不能为空');
        }
    }

    // 判断用户是否存在
    $sql = 'select * from users where id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_POST['user_id']]);
    $res = $stmt->fetch(PDO::FETCH_ASSOC);
    if (empty($res)) {
        throw new Exception('用户不存在，请重新登录');
    }

    // 判断文章是否存在
    $sql = 'select * from articles where id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_POST['article_id']]);
    $res = $stmt->fetch(PDO::FETCH_ASSOC);
    if (empty($res)) {
        throw new Exception('文章不存在，无法评论');
    }

    // 插入评论
    $sql = 'insert into comments (user_id, article_id, content) values (?, ?, ?)';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_POST['user_id'], $_POST['article_id'], $_POST['content']]);
    if ($stmt->rowCount() <= 0) {
        throw new Exception('评论失败');
    }

    myResponse('', 1, 200);
} catch (Exception $e) {
    myResponse($e->getMessage(), 0, 200);
}